﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfAppTimes
{
    /// <summary>
    /// KeHuDuan.xaml 的交互逻辑
    /// </summary>
    public partial class KeHuDuan : Window
    {

        Socket clientSocket;
        
        
        public KeHuDuan()
        {
            InitializeComponent();
            Thread thread2 = new Thread(jieShou);
            thread2.Start();
        }
        public void peiZhiSocket()
        {
            App.Current.Dispatcher.Invoke((Action)(() =>
            {
                try
                {
                    //获取用户输入信息
                    string sip = id_text.Text;
                    int dk = Convert.ToInt32(duankou_text.Text);
                    //xingXiJiLu.AppendText("ip:" + sip +"dk:"+dk+"\n");
                    //设定服务器IP地址  
                    IPAddress ip = IPAddress.Parse(sip);
                    clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    clientSocket.Connect(new IPEndPoint(ip, dk)); //配置服务器IP与端口  
                    Console.WriteLine("连接服务器成功");
                    xiaoXi.Content = "连接服务器成功!";
                    isthread2 = true;
                    xingXiJiLu.AppendText("开始接收信息"+ "\n");
                }
                catch
                {
                    Console.WriteLine("连接服务器失败，请按回车键退出！");
                    xiaoXi.Content = "连接服务器失败...";
                    return;
                }
            }));

        }

        

        public void faSong(object str)
        {
            App.Current.Dispatcher.Invoke((Action)(() =>
            {
                clientSocket.Send(Encoding.UTF8.GetBytes(str.ToString()));//向服务器发送数据，需要发送中文则需要使用Encoding.UTF8.GetBytes()，否则会乱码
            Console.WriteLine("向服务器发送消息：" + str);
            }));
        }

        Boolean isthread2 = false;
        public void jieShou()
        {
                while (true)
                {
                    Thread.Sleep(1000);
                    if (isthread2){
                        try{
                            //Thread.Sleep(1000);
                            string time = DateTime.Now.ToString("HH:mm:ss");
                            //接受从服务器返回的信息
                            string recvStr = "";
                            byte[] recvBytes = new byte[1024];
                            int bytes;
                            bytes = clientSocket.Receive(recvBytes, recvBytes.Length, 0);    //从服务器端接受返回信息 
                            recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes);
                            Console.WriteLine("接收消息！"+ recvStr+"时间："+time);
                            setxingXiJiLu(time, recvStr);
                        //xingXiJiLu.ScrollToEnd();
                        //return recvStr;
                    }catch
                        {
                            Console.WriteLine("接收消息出错！");
                        }
                    }else
                    {
                        //Thread.Sleep(1000);
                        //Console.WriteLine("线程处于：Lfales");
                    }
                }      
        }
        public void setxingXiJiLu(string time,string str)
        {
            App.Current.Dispatcher.Invoke((Action)(() =>
            {
                xingXiJiLu.AppendText("时间：" + time + "  信息:" + str + "\n");
                xingXiJiLu.ScrollToEnd();
            }));
        }
        public void gogo()
        {
            Thread thread = new Thread(peiZhiSocket);
            xiaoXi.Content = "等待配置连接服务器";
            thread.Start();
        }
        private void LianJIe_Click(object sender, RoutedEventArgs e)
        {
            gogo();
        }

        private void FaSongAnNiu_Click(object sender, RoutedEventArgs e)
        {
            string str = neirong_text.Text+"\n";
            faSong(str);
            setxingXiJiLu("","发送消息："+ str);
        }
    }
}

